package org.changs.aplug.utils;

import android.support.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by yincs on 2016/11/6.
 */

public class JsonUtils {

    private static final Gson gson = new Gson();

    static {

    }

    public static Gson getMapper() {
        return gson;
    }


    @Nullable
    public static <T> T parseObject(String json, Class<T> clazz) {
        if (EmptyUtils.isEmpty(json)) return null;
        try {
            return gson.fromJson(json, clazz);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Json转List集合
     */
    @Nullable
    public static <T> List<T> parseList(String json) {
        if (EmptyUtils.isEmpty(json)) return null;
        Type type = new TypeToken<List<T>>() {
        }.getType();
        try {
            return gson.fromJson(json, type);
        } catch (Exception e) {
            return null;
        }

    }


    /**
     * 转成Json字符串
     */
    @Nullable
    public static String stringify(Object object) {
        if (object == null) return null;
        try {
            return gson.toJson(object);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * Json转List集合,遇到解析不了的，就使用这个
     */
    public static <T> List<T> fromJsonList(String json, Class<T> cls) {
        List<T> mList = new ArrayList<T>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        Gson mGson = new Gson();
        for (final JsonElement elem : array) {
            mList.add(mGson.fromJson(elem, cls));
        }
        return mList;
    }

    /**
     * Json转换成Map的List集合对象
     */
    public static <T> List<Map<String, T>> toListMap(String json, Class<T> clz) {
        Type type = new TypeToken<List<Map<String, T>>>() {
        }.getType();
        return gson.fromJson(json, type);
    }

    /**
     * Json转Map对象
     */
    public static <T> Map<String, T> toMap(String json, Class<T> clz) {
        Type type = new TypeToken<Map<String, T>>() {
        }.getType();
        return gson.fromJson(json, type);
    }


}
